// @ts-ignore
import type { Settings as LayoutSettings } from '@ant-design/pro-layout'
// @ts-ignore
import { SettingDrawer } from '@ant-design/pro-layout'
// @ts-ignore
import type { RunTimeLayoutConfig } from 'umi'
// @ts-ignore
import { history, getDvaApp } from '@umijs/max'
import { routeDarkList } from './contants'
import defaultSettings from '../config/defaultSettings'

// @ts-ignore
import Tools from '@/utils/Tools'

const titleInfo = localStorage.getItem('titleInfo') && JSON.parse(localStorage.getItem('titleInfo')) || {}

const Bus = Tools.Bus
// @ts-ignore
export const dva = {
  config: {
    onError(e) {
      e.preventDefault()
      console.error(e.message)
    },
  },
}

// @ts-ignore
window.dataServiceApiManageProduceApiCreateRes = (data) => {
  Bus.emit('/data-service/api-manage/produce-api-create/res', data)
}
// @ts-ignore
window.dataServiceApiManageProduceApiCreateReq = (data) => {
  Bus.emit('/data-service/api-manage/produce-api-create/req', data)
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  loading?: boolean;
}> {
  return {
    loading: true,
    settings: defaultSettings,
  }
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  // @ts-ignore
  const { dispatch } = getDvaApp()._store
  Bus.addListener('layout_set_state', (settings) => {
    setInitialState && setInitialState((preInitialState) => ({
      ...preInitialState,
      loading: false,
      settings,
    }))
  })
  return {
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    onPageChange: () => {
      const { location } = history
      const nowInChoose = routeDarkList.includes(location.pathname)
      dispatch({ type: 'global/routeDarkChoose', data: { inChoose: nowInChoose } })
      // 当路由初始化 或 路由变化时，控制themeValue的变化
      if (!nowInChoose) {
        // 如果不在被选路由下，一律使用' light '
        // 不改变localStorage
        dispatch({ type: 'global/themeChange', data: { themeValue: 'light' } })
        return
      }
      // 如果在处在被选路由下
      const theThemeValue = localStorage.getItem('themeValue') || 'light'
      if (!theThemeValue) {
        // 未拥有localStorage,初始化为global.themeValue的值
        localStorage.setItem('themeValue', global.themeValue)
      } else if (theThemeValue !== global.themeValue) {
        // 将themeValue以localStorage的值作为准值
        dispatch({ type: 'global/themeChange', data: { themeValue: theThemeValue } })
      }
    },
    headerHeight: 0,
    headerRender: false,
    menuHeaderRender: false,
    pageTitleRender: false,
    headerTitleRender: false,
    menuRender: false,
    title: titleInfo?.companyName || '-',
    // @ts-ignore
    childrenRender: (children, props) =>
      // if (initialState?.loading) return <PageLoading />;
      (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <div className="DisplayNone">
              <SettingDrawer
                disableUrlParams
                enableDarkTheme
                settings={initialState?.settings}
                onSettingChange={(settings) => {
                  setInitialState && setInitialState((preInitialState) => ({
                    ...preInitialState,
                    settings,
                  }))
                }}
              />
            </div>
          )}
        </>
      ),
    ...initialState?.settings,
  }
}
